package com.dy.security.filter;

import org.springframework.http.HttpMethod;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName:
 * @Author: dingyu
 * @Desctiption: (描述) 自定义用户校验验证码的过滤器
 * @Date: 2022/3/31 13:42
 * @Version 1.0 (版本)
 */
public class VerificationCodeFilter extends OncePerRequestFilter {
    private static final String LOGIN_RUL="/login";
    private static final String KAPTCHA="kaptcha";
    private static final String CODE="code";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //只处理用户登录请求
        if (LOGIN_RUL.equals(request.getRequestURI()) && request.getMethod().equals(HttpMethod.POST.name())) {
            if (this.verifyCode(request)) {
                System.out.println(" 验证通过 ");
                filterChain.doFilter(request,response);
            }else{
                response.getWriter().write("验证失败！");
            }
        }else{
            System.err.println(" 验证失败 ");
            filterChain.doFilter(request,response);
        }
    }

    /**
     * 验证码校验
     * @param request request
     * @return Boolean
     */
    private Boolean verifyCode(HttpServletRequest request){
        //获取用户传来的验证码信息，比较session中的验证码信息是否一致
        //1.从session中获取验证码信息
        String kaptcha = (String)request.getSession().getAttribute(KAPTCHA);
        //2.从表单的参数中获取到用户输入的验证码
        String code = request.getParameter(CODE);
        //3.比较session中的验证码是否和用户输入的验证码一致
        if (StringUtils.isEmpty(code)) {
            //清空session中的验证码，让用户重新获取
            request.removeAttribute(KAPTCHA);
            return false;
        }
        if (!code.equals(kaptcha)) {
            return false;
        }
        return true;
    }
}
